$(function () {
    init_menu_form();
});

/**初始化表单类型**/
function init_menu_form() {
    //初始化验证数据
    var $menuAddForm = $("#menu-add-form");
    var icon = "<i class='zmdi zmdi-close-circle zmdi-hc-fw'></i> ";
   $menuAddForm.validate({
        rules: {
            menuName: {
                required: true,
                minlength: 2,
                maxlength: 10,
                remote: {
                    url: "menu/checkMenuName",
                    type: "get",
                    dataType: "json",
                    data: {
                        menuName: function () {
                            return $("input[name='menuName']").val().trim();
                        },
                        type: function () {
                            return $("input[name='type']").val();
                        }
                    }
                }
            }
        },
        messages: {
            menuName: {
                required: icon + "请输入名称",
                minlength: icon + "名称长度2到10个字符",
                remote: icon + "该名称已经存在"
            }
        }
    });
   //初始化菜单栏的数据
    $.post(ctx + "menu/tree", {}, function (r) {
        if (r.code === 0) {
            var data = r.msg;
            $('#menuTree').jstree({
                "core": {
                    'data': data.children,
                    'multiple': false
                },
                "state": {
                    "disabled": true
                },
                "checkbox": {
                    "three_state": false
                },
                "plugins": ["wholerow", "checkbox"]
            });
        } else {
            $JuXue.n_danger(r.msg);
        }
    });
    var $menuName = $menuAddForm.find("input[name='menuName']");
    //初始化类型切换
    $menuAddForm.find("input[name='type']").change(function () {
        var $value = $menuAddForm.find("input[name='type']:checked").val();
        if ($value === "0") {
            $menuName.parent().prev().text("菜单名称：");
        } else {
            $menuName.parent().prev().text("按钮名称：");
        }
    });
}

/**保存数据**/
function saveMenuInfo() {
    var $menuAddForm = $("#menu-add-form");
    var ref = $('#menuTree').jstree(true);
    $("[name='parentId']").val(ref.get_checked()[0]);

    var validator = $menuAddForm.validate();
    var flag = validator.form();
    if (flag) {
        $.post(ctx + "menu/add", $menuAddForm.serialize(), function (r) {
            if (r.code === 0) {
                $JuXue.n_success(r.msg);
                $("#menu_info").modal("hide");
                Menu_refresh();
            } else $JuXue.n_danger(r.msg);
        });
    }
}
